import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import { DataManagementService } from '../data-management.services';
import { NotificationService } from 'app/shared/service';
import * as moment from 'moment';
import { PublicService } from 'app/public/public.service';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'itmp-traffic-accident-report',
    templateUrl: './traffic-accident-report.component.html',
    styleUrls: ['./traffic-accident-report.component.css']
})
export class TrafficAccidentReportComponent implements OnInit {
    queryStartTime = null; // 开始日期
    queryEndTime = null; // 结束日期
    renderStatistical = null;
    renderHeader = null; // 表头数据的数组
    listOfData = []; // 列表数据的数组
    listData = []; // 列表数据的数组
    pagination = {
        totalEle: 0,
        pageSize: 10,
        currentPage: 1,
        currentSize: 10
    };
    dateRange = null; // 横坐标的值
    isEchartsShow = false;
    isShowTable = false;
    intervalSelect = null;
    sourcelSelect = 'current';
    fatal_total_num = [];
    major_total_num = [];
    minor_total_num = [];
    minor_avg_cleartime = [];
    fatal_avg_cleartime = [];
    major_avg_cleartime = [];
    intervalOptions = [];
    interval_zone = [];
    year_interval_zone = [];
    mounth_interval_zone = [];
    options: EChartOption;
    echartsIntance: any;
    flag = false;
    accessButton = {
        Create: false,
        Edit: false,
        Delete: false,
        PRINT: false
    };
    constructor(
        private DMService: DataManagementService,
        private message: NotificationService,
        private pub: PublicService,
        private translate: TranslateService
    ) {}

    ngOnInit() {
        this.initDefaultData();
        this.getData(this.initDefaultData());
        this.getOption();
        this.renderHeader = [
            {
                name: 'Date',
                key: null,
                value: 'date'
            },
            {
                name: 'Minor',
                key: null,
                value: 'minor'
            },
            {
                name: 'Major',
                key: null,
                value: 'major'
            },
            {
                name: 'Fatal',
                key: null,
                value: 'fatal'
            },
            {
                name: 'Sum',
                key: null,
                value: 'sum'
            }
        ];
        this.renderStatistical = [
            {
                name: 'NumCases',
                key: null,
                value: 'NumCases'
            },
            {
                name: 'AvgClearance',
                key: null,
                value: 'AvgClearance'
            },
            {
                name: 'NumCases',
                key: null,
                value: 'NumCases'
            },
            {
                name: 'AvgClearance',
                key: null,
                value: 'AvgClearance'
            },
            {
                name: 'NumCases',
                key: null,
                value: 'NumCases'
            },
            {
                name: 'AvgClearance',
                key: null,
                value: 'AvgClearance'
            },
            {
                name: 'NumCases',
                key: null,
                value: 'NumCases'
            },
            {
                name: 'AvgClearance',
                key: null,
                value: 'AvgClearance'
            }
        ];
        this.intervalOptions = [{ name: 'year-month', id: 'yy' }, { name: 'month-week', id: 'mm' }, { name: 'week-day', id: 'wk' }];
        this.getButtonAccess();
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('28', this.accessButton);
    }
    onChartInit(ec: any) {
        this.echartsIntance = ec;
    }
    getOption() {
        const tempData = ['Minor', 'Major', 'Fatal'];
        const translateData = [];
        tempData.forEach(item => {
            this.translate.get('DataManagement.TrafficAccidentReport.' + item).subscribe((res: string) => {
                translateData.push(res);
            });
        });
        setTimeout(() => {
            this.options = {
                tooltip: {
                    trigger: 'item',
                    formatter(params) {
                        let str = params['name'] + ' ';
                        str += params['seriesName'] + ':' + Math.abs(params['value']);
                        return str;
                    }
                },
                legend: {
                    itemWidth: 15,
                    itemHeight: 15,
                    // radius: 30,
                    data: translateData,
                    // left: 'right',
                    right: '2%',
                    textStyle: {
                        color: '#ffffff' //图例颜色
                    }
                },
                xAxis: [
                    {
                        data:
                            this.intervalSelect === 'yy'
                                ? this.year_interval_zone
                                : this.intervalSelect === 'mm' ? this.mounth_interval_zone : this.interval_zone,
                        splitLine: {
                            show: true
                        },
                        axisLine: {
                            lineStyle: {
                                color: 'ffffff' //轴线颜色
                            }
                        },
                        axisLabel: {
                            show: true,
                            textStyle: {
                                //x轴座标文字颜色
                                color: '#fff'
                            }
                        }
                    }
                ],
                yAxis: {
                    splitLine: {
                        show: true
                    },
                    splitArea: { show: false },
                    axisLabel: {
                        formatter(data) {
                            return Math.abs(data);
                        },
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'ffffff' //轴线颜色
                        }
                    }
                },
                series: [
                    {
                        name: translateData[0],
                        type: 'bar',
                        stack: 'one',
                        barWidth: 40,
                        data: this.minor_avg_cleartime,
                        itemStyle: {
                            normal: { color: '#555556' }
                        }
                    },
                    {
                        name: translateData[1],
                        type: 'bar',
                        barWidth: 40,
                        stack: 'one',
                        data: this.major_avg_cleartime,
                        itemStyle: {
                            normal: { color: '#333333' }
                        }
                    },
                    {
                        name: translateData[2],
                        type: 'bar',
                        barWidth: 40,
                        stack: 'one',
                        data: this.fatal_avg_cleartime,
                        itemStyle: {
                            normal: { color: '#238CE6' }
                        }
                    },
                    {
                        name: translateData[0],
                        type: 'bar',
                        stack: 'one',
                        barWidth: 40,
                        data: this.minor_total_num,
                        itemStyle: {
                            normal: { color: '#555556' }
                        }
                    },
                    {
                        name: translateData[1],
                        type: 'bar',
                        stack: 'one',
                        barWidth: 40,
                        data: this.major_total_num,
                        itemStyle: {
                            normal: { color: '#333333' }
                        }
                    },
                    {
                        name: translateData[3],
                        type: 'bar',
                        stack: 'one',
                        barWidth: 40,
                        data: this.fatal_total_num,
                        itemStyle: {
                            normal: { color: '#238CE6' }
                        }
                    }
                ],
                dataZoom: [
                    {
                        type: 'slider',
                        show: false,
                        // start: 0,
                        // end: 50,
                        handleSize: 8
                    },
                    {
                        type: 'inside'
                        // start: 0,
                        // end: 50
                    }
                    // {
                    //     type: 'slider',
                    //     show: true,
                    //     yAxisIndex: [0],
                    //     left: '93%',
                    //     start: 29,
                    //     end: 36
                    // },
                ]
            };
        });
    }
    search() {
        // tslint:disable-next-line:max-line-length
        if (this.queryStartTime === null || this.queryEndTime === null || this.intervalSelect === null) {
            this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.select_notify' });
        } else {
            const queryData = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},interval=${this.intervalSelect}`;
            // 获取报表数据
            this.DMService.getTraAccRep(queryData).subscribe(res => {
                if (res.messagecode === '000000') {
                    // 将获取到的数据进行封装为自己需要的格式
                    const map = {};
                    const dest = [];
                    res.data.forEach((item, i) => {
                        const ai = res.data[i];
                        if (!map[ai.interval_zone]) {
                            dest.push({
                                interval_zone: ai.interval_zone,
                                data: [ai]
                            });
                            map[ai.interval_zone] = ai;
                        } else {
                            dest.forEach((it, j) => {
                                const dj = dest[j];
                                if (dj.interval_zone === ai.interval_zone) {
                                    dj.data.push(ai);
                                }
                            });
                        }
                    });
                    const data = [];
                    for (const item of dest) {
                        data.push({
                            interval_zone: item.data[0].interval_zone,
                            fatal_accident_level: item.data[0].accident_level,
                            fatal_total_num: item.data[0].total_num,
                            fatal_avg_cleartime: item.data[0].avg_cleartime,
                            major_accident_level: item.data[1].accident_level,
                            major_total_num: item.data[1].total_num,
                            major_avg_cleartime: item.data[1].avg_cleartime,
                            minor_accident_level: item.data[2].accident_level,
                            minor_total_num: item.data[2].total_num,
                            minor_avg_cleartime: item.data[2].avg_cleartime,
                            sum_total_num: (
                                parseInt(item.data[0].total_num) +
                                parseInt(item.data[1].total_num) +
                                parseInt(item.data[2].total_num)
                            ).toString(),
                            sum_avg_cleartime: (
                                parseInt(item.data[0].avg_cleartime) +
                                parseInt(item.data[1].avg_cleartime) +
                                parseInt(item.data[2].avg_cleartime)
                            ).toString()
                        });
                    }
                    this.minor_total_num = [];
                    this.fatal_total_num = [];
                    this.major_total_num = [];
                    this.minor_avg_cleartime = [];
                    this.fatal_avg_cleartime = [];
                    this.major_avg_cleartime = [];
                    this.interval_zone = [];
                    this.year_interval_zone = [];
                    this.mounth_interval_zone = [];
                    for (const item of data) {
                        const mounthTemporaryTime = [];
                        this.minor_total_num.push(-item.minor_total_num);
                        this.fatal_total_num.push(-item.fatal_total_num);
                        this.major_total_num.push(-item.major_total_num);
                        this.minor_avg_cleartime.push(item.minor_avg_cleartime.toString());
                        this.fatal_avg_cleartime.push(item.fatal_avg_cleartime.toString());
                        this.major_avg_cleartime.push(item.major_avg_cleartime.toString());
                        this.interval_zone.push(item.interval_zone);
                        this.year_interval_zone.push(item.interval_zone.split('-')[0]); // 组装成年份时间
                        item.interval_zone.split('~').forEach(time => {
                            // 组装出月份时间
                            const temporaryTime = time.split('-');
                            temporaryTime.splice(2, 1);
                            mounthTemporaryTime.push(temporaryTime.join('-'));
                        });
                        this.mounth_interval_zone.push(mounthTemporaryTime.join('~'));
                    }
                    if (res.data.length === 0) {
                        this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                        this.isEchartsShow = false;
                    } else {
                        this.isEchartsShow = true;
                    }
                    this.getOption();
                    // this.options.xAxis[0].data = [];
                    // this.options.xAxis[0].data = this.interval_zone;
                    // this.getOption();
                    // this.echartsIntance.setOption(this.options, true);
                }
            });
            // 获取分页数据
            const searchData = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},interval=${this.intervalSelect}`;
            const pageNum = this.pagination.currentPage;
            const pageSize = this.pagination.pageSize * 3;
            this.DMService.getTraAccRepTable(searchData, pageNum, pageSize).subscribe(res => {
                if (res.messagecode === '000000') {
                    const map = {};
                    const dest = [];
                    if (res.data.content.length === 0) {
                        this.isShowTable = false;
                    } else {
                        this.isShowTable = true;
                    }
                    res.data.content.forEach((item, i) => {
                        const ai = res.data.content[i];
                        if (!map[ai.interval_zone]) {
                            dest.push({
                                interval_zone: ai.interval_zone,
                                data: [ai]
                            });
                            map[ai.interval_zone] = ai;
                        } else {
                            dest.forEach((it, j) => {
                                const dj = dest[j];
                                if (dj.interval_zone === ai.interval_zone) {
                                    dj.data.push(ai);
                                }
                            });
                        }
                    });
                    const data = [];
                    for (const item of dest) {
                        const mounthTemporaryTime = [];
                        item.data[0].interval_zone.split('~').forEach(time => {
                            // 组装出月份时间
                            const temporaryTime = time.split('-');
                            temporaryTime.splice(2, 1);
                            mounthTemporaryTime.push(temporaryTime.join('-'));
                        });
                        data.push({
                            interval_zone: item.data[0].interval_zone,
                            year_interval_zone: item.data[0].interval_zone.split('-')[0],
                            mounth_interval_zone: mounthTemporaryTime.join('~'),
                            fatal_accident_level: item.data[0].accident_level,
                            fatal_total_num: item.data[0].total_num,
                            fatal_avg_cleartime: item.data[0].avg_cleartime,
                            major_accident_level: item.data[1].accident_level,
                            major_total_num: item.data[1].total_num,
                            major_avg_cleartime: item.data[1].avg_cleartime,
                            minor_accident_level: item.data[2].accident_level,
                            minor_total_num: item.data[2].total_num,
                            minor_avg_cleartime: item.data[2].avg_cleartime,
                            sum_total_num: (
                                parseInt(item.data[0].total_num) +
                                parseInt(item.data[1].total_num) +
                                parseInt(item.data[2].total_num)
                            ).toString(),
                            sum_avg_cleartime: (
                                parseInt(item.data[0].avg_cleartime) +
                                parseInt(item.data[1].avg_cleartime) +
                                parseInt(item.data[2].avg_cleartime)
                            ).toString()
                        });
                    }
                    this.listOfData = data;
                    this.pagination.currentPage = res.data.pageNum;
                    this.pagination.currentSize = res.data.numberOfElements / 3;
                    this.pagination.totalEle = res.data.totolElements / 3;
                }
            });
        }
    }
    initDefaultData() {
        // 获取当天日期三月前
        const day2 = new Date();
        day2.setTime(day2.getTime());
        const beforeYear = moment()
            .subtract(3, 'months')
            .format('YYYY-MM-DD');
        const threeDay = beforeYear + '-' + (day2.getMonth() - 2) + '-' + day2.getDate();
        // 获取当天日期
        const day1 = new Date();
        day1.setTime(day1.getTime());
        const thisDay = day1.getFullYear() + '-' + (day1.getMonth() + 1) + '-' + day1.getDate();
        this.dateRange = [beforeYear, thisDay];
        this.intervalSelect = 'wk';
        // 默认请求当前日期三个月之前数据，按周查询
        this.queryStartTime = beforeYear;
        this.queryEndTime = thisDay;
        const queryData = `startDateRange=${beforeYear},endDateRange=${thisDay},interval=wk`;
        return queryData;
    }
    getData(queryData: string) {
        // 搜索实时数据禁用筛选框
        // if (this.sourcelSelect === 'current') {
        //     this.flag = true;
        // } else {
        //     this.flag = false;
        // }
        this.DMService.getTraAccRep(queryData).subscribe(res => {
            if (res.messagecode === '000000') {
                // 将获取到的数据进行封装为自己需要的格式
                const map = {};
                const dest = [];
                res.data.forEach((item, i) => {
                    const ai = res.data[i];
                    if (!map[ai.interval_zone]) {
                        dest.push({
                            interval_zone: ai.interval_zone,
                            data: [ai]
                        });
                        map[ai.interval_zone] = ai;
                    } else {
                        dest.forEach((it, j) => {
                            const dj = dest[j];
                            if (dj.interval_zone === ai.interval_zone) {
                                dj.data.push(ai);
                            }
                        });
                    }
                });
                const data = [];
                for (const item of dest) {
                    const mounthTemporaryTime = [];
                    item.data[0].interval_zone.split('~').forEach(time => {
                        // 组装出月份时间
                        const temporaryTime = time.split('-');
                        temporaryTime.splice(2, 1);
                        mounthTemporaryTime.push(temporaryTime.join('-'));
                    });
                    data.push({
                        interval_zone: item.data[0].interval_zone,
                        year_interval_zone: item.data[0].interval_zone.split('-')[0],
                        mounth_interval_zone: mounthTemporaryTime.join('~'),
                        fatal_accident_level: item.data[0].accident_level,
                        fatal_total_num: item.data[0].total_num,
                        fatal_avg_cleartime: item.data[0].avg_cleartime,
                        major_accident_level: item.data[1].accident_level,
                        major_total_num: item.data[1].total_num,
                        major_avg_cleartime: item.data[1].avg_cleartime,
                        minor_accident_level: item.data[2].accident_level,
                        minor_total_num: item.data[2].total_num,
                        minor_avg_cleartime: item.data[2].avg_cleartime,
                        sum_total_num: (
                            parseInt(item.data[0].total_num) +
                            parseInt(item.data[1].total_num) +
                            parseInt(item.data[2].total_num)
                        ).toString(),
                        sum_avg_cleartime: (
                            parseInt(item.data[0].avg_cleartime) +
                            parseInt(item.data[1].avg_cleartime) +
                            parseInt(item.data[2].avg_cleartime)
                        ).toString()
                    });
                }
                for (const item of data) {
                    this.minor_total_num.push(-item.minor_total_num);
                    this.fatal_total_num.push(-item.fatal_total_num);
                    this.major_total_num.push(-item.major_total_num);
                    this.minor_avg_cleartime.push(item.minor_avg_cleartime.toString());
                    this.fatal_avg_cleartime.push(item.fatal_avg_cleartime.toString());
                    this.major_avg_cleartime.push(item.major_avg_cleartime.toString());
                    this.interval_zone.push(item.interval_zone);
                }
            }
            if (res.data.length === 0) {
                this.message.notify({ type: 'warning', path: 'DataManagement.TrafficDataReport.nodata' });
                this.isEchartsShow = false;
            } else {
                this.isEchartsShow = true;
            }
            this.getOption();
            // this.echartsIntance.setOption(this.options, true);
        });
        this.getTableData(queryData);
    }
    getTableData(queryData: string) {
        // 获取分页数据
        const pageNum = this.pagination.currentPage;
        const pageSize = this.pagination.pageSize * 3;
        this.DMService.getTraAccRepTable(queryData, pageNum, pageSize).subscribe(res => {
            if (res.messagecode === '000000') {
                if (res.data.content.length === 0) {
                    this.isShowTable = false;
                } else {
                    this.isShowTable = true;
                }
                const map = {};
                const dest = [];
                res.data.content.forEach((item, i) => {
                    const ai = res.data.content[i];
                    if (!map[ai.interval_zone]) {
                        dest.push({
                            interval_zone: ai.interval_zone,
                            data: [ai]
                        });
                        map[ai.interval_zone] = ai;
                    } else {
                        dest.forEach((it, j) => {
                            const dj = dest[j];
                            if (dj.interval_zone === ai.interval_zone) {
                                dj.data.push(ai);
                            }
                        });
                    }
                });
                const data = [];
                for (const item of dest) {
                    const mounthTemporaryTime = [];
                    item.data[0].interval_zone.split('~').forEach(time => {
                        // 组装出月份时间
                        const temporaryTime = time.split('-');
                        temporaryTime.splice(2, 1);
                        mounthTemporaryTime.push(temporaryTime.join('-'));
                    });
                    data.push({
                        interval_zone: item.data[0].interval_zone,
                        year_interval_zone: item.data[0].interval_zone.split('-')[0],
                        mounth_interval_zone: mounthTemporaryTime.join('~'),
                        fatal_accident_level: item.data[0].accident_level,
                        fatal_total_num: item.data[0].total_num,
                        fatal_avg_cleartime: item.data[0].avg_cleartime,
                        major_accident_level: item.data[1].accident_level,
                        major_total_num: item.data[1].total_num,
                        major_avg_cleartime: item.data[1].avg_cleartime,
                        minor_accident_level: item.data[2].accident_level,
                        minor_total_num: item.data[2].total_num,
                        minor_avg_cleartime: item.data[2].avg_cleartime,
                        sum_total_num: (
                            parseInt(item.data[0].total_num) +
                            parseInt(item.data[1].total_num) +
                            parseInt(item.data[2].total_num)
                        ).toString(),
                        sum_avg_cleartime: (
                            parseInt(item.data[0].avg_cleartime) +
                            parseInt(item.data[1].avg_cleartime) +
                            parseInt(item.data[2].avg_cleartime)
                        ).toString()
                    });
                }
                this.minor_total_num = [];
                this.fatal_total_num = [];
                this.major_total_num = [];
                this.interval_zone = [];
                this.listOfData = data;
                this.pagination.currentPage = res.data.pageNum;
                this.pagination.currentSize = res.data.numberOfElements / 3;
                this.pagination.totalEle = res.data.totolElements / 3;
            }
        });
    }
    // 分页控件改变事件
    onPageChange(e) {
        this.pagination.currentPage = e;
        const queryData = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},interval=wk`;
        this.getTableData(queryData);
    }
    onSizeChange(e) {
        this.pagination.pageSize = e;
        const queryData = `startDateRange=${this.queryStartTime},endDateRange=${this.queryEndTime},interval=wk`;
        this.getTableData(queryData);
    }
    onOk(result: Date): void {}
    onChange(result: Date): void {
        const startDate = new Date(result[0]).getTime();
        const endDate = new Date(result[1]).getTime();
        const t1 = moment(startDate).format('YYYY-MM-DD');
        const t2 = moment(endDate).format('YYYY-MM-DD');
        // this.queryStartTime = t1;
        // this.queryEndTime = t2;
        let month = t1.split('-')[1];
        let day = t1.split('-')[2];
        const year = t1.split('-')[0];
        let month1 = t2.split('-')[1];
        let day1 = t2.split('-')[2];
        const year1 = t2.split('-')[0];
        if (month.includes('0')) {
            month = month.replace(/\b(0+)/gi, '');
        }
        if (day.includes('0')) {
            day = day.replace(/\b(0+)/gi, '');
        }
        if (month1.includes('0')) {
            month1 = month1.replace(/\b(0+)/gi, '');
        }
        if (day1.includes('0')) {
            day1 = day1.replace(/\b(0+)/gi, '');
        }
        this.queryStartTime = year + '-' + month + '-' + day;
        this.queryEndTime = year1 + '-' + month1 + '-' + day1;
    }
    // 定义几个筛选下拉框，防止页面报错
    public intervalSearch() {
        this.search();
    }
    public sourceSearch() {
        // 搜索实时数据禁用筛选框
        // if (this.sourcelSelect === 'current') {
        //     this.flag = true;
        // } else {
        //     this.flag = false;
        // }
    }
    // 禁用今天之后的日期选择
    range(start: number, end: number): number[] {
        const result: number[] = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };

    disabledDateTime: object = () => {
        return {
            nzDisabledHours: () => this.range(0, 24).splice(4, 20),
            nzDisabledMinutes: () => this.range(30, 60),
            nzDisabledSeconds: () => [55, 56]
        };
    };

    disabledRangeTime: object = (value: Date[], type: 'start' | 'end') => {
        if (type === 'start') {
            return {
                nzDisabledHours: () => this.range(0, 60).splice(4, 20),
                nzDisabledMinutes: () => this.range(30, 60),
                nzDisabledSeconds: () => [55, 56]
            };
        }
        return {
            nzDisabledHours: () => this.range(0, 60).splice(20, 4),
            nzDisabledMinutes: () => this.range(0, 31),
            nzDisabledSeconds: () => [55, 56]
        };
    };
}
